<template>
  <div class="v-select-input">
    <el-select v-model="value" :placeholder="placeholder1" :style="{ width: `${width}px`, height: `${height}px` }"
               popper-class="v-select-input" @visible-change="clearInputVal" @change="change">
      <div class="v-input">
        <el-input v-model="inputVal" :placeholder="placeholder2">
          <i slot="prefix" class="iconfont icon-search"></i>
        </el-input>
      </div>
      <el-option
        v-for="item in options"
        :key="getItemKey(item)"
        :label="getItemVal(item)"
        :value="getItemKey(item)">
      </el-option>
    </el-select>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    props: {
      options: {
        type: Array
      },
      selValue: {
        type: String,
        default: ''
      },
      inputValue: {
        type: String,
        default: ''
      },
      placeholder1: {
        type: String,
        default: '请选择'
      },
      placeholder2: {
        type: String,
        default: '请在此输入'
      },
      width: {
        type: Number,
        default: 200
      },
      height: {
        type: Number,
        default: 30
      },
      itemKey: {
        type: String,
        default: 'value'
      },
      itemValue: {
        type: String,
        default: 'label'
      }
    },
    data () {
      return {
        value: '',
        inputVal: ''
      }
    },
    watch: {
      inputVal (val) {
        if (val) {
          this.$emit('on-watch', val)
        }
      }
    },
    methods: {
      change (val) {
        this.options.forEach((item) => {
          if (item[this.itemKey] === val) {
            this.$emit('on-change', item)
          }
        })
      },
      clearInputVal (val) {
        this.inputVal = ''
      },
      getItemKey (item) {
        for (let key in item) {
          if (key === this.itemKey) {
            return item[this.itemKey]
          }
        }
      },
      getItemVal (item) {
        for (let key in item) {
          if (key === this.itemValue) {
            return item[this.itemValue]
          }
        }
      }
    },
    created () {
      this.value = this.selValue
      this.inputVal = this.inputValue
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  .v-select-input
    .el-input
      height 100%
      font-size 12px
      .el-input__inner
        height 100%
        font-size 12px
    .el-scrollbar
      .v-input
        width 100%
        padding 0 10px
        .el-input
          width 100%
          height 30px
          margin-bottom 10px
          .el-input__inner
            height 30px !important
            font-size 12px
          .iconfont
            position absolute
            top 2px
</style>
